package com.music.playlist.controllers;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.music.client.playlist.client.PlaylistClient;
import com.music.service.members.beans.Member;
import com.music.service.playlists.beans.Playlist;

public class ViewPlaylistController  implements Controller {

	private PlaylistClient mPlaylistClient;
	
	private String mViewName;
	private String mExceptionView;
	
	public ModelAndView handleRequest(HttpServletRequest pRequest,HttpServletResponse pResponse) 
					throws ServletException, IOException {
		
		ModelAndView modelAndView = new ModelAndView();
		Long pMemberId = null;
		Long pPlaylistId = null;
		try{
			pMemberId = getMemberId(pRequest);
			pPlaylistId = Long.valueOf(pRequest.getParameter("pid"));
		}catch(NumberFormatException nfe){
			modelAndView.setViewName(getExceptionView());
			modelAndView.addObject("exceptionMsg","Invalid Member Id or Playlist Id");
			return modelAndView;
		}	
		
		Playlist playlist = getPlaylistClient().getPlaylistSongsForMember(pMemberId, pPlaylistId);
		List<Playlist> recentPlaylist = getPlaylistClient().getRecentPlaylists(pMemberId);
		
		modelAndView.addObject("playlist",playlist);
		modelAndView.addObject("recentPlaylist",recentPlaylist);
		modelAndView.setViewName(getViewName());
		
		return modelAndView;
	}
	
	/**
	 * 
	 * @param pRequest
	 * @return
	 */
	private Long getMemberId(HttpServletRequest pRequest){
		Member member = (Member) pRequest.getAttribute("member");
		return member.getMemberId();
	}
	
	/**
	 * @return the viewName
	 */
	public String getViewName() {
		return mViewName;
	}

	/**
	 * @param pViewName the viewName to set
	 */
	@Required
	public void setViewName(String pViewName) {
		mViewName = pViewName;
	}

	/**
	 * @return the playlistClient
	 */
	public PlaylistClient getPlaylistClient() {
		return mPlaylistClient;
	}

	/**
	 * @param pPlaylistClient the playlistClient to set
	 */
	@Required
	public void setPlaylistClient(PlaylistClient pPlaylistClient) {
		mPlaylistClient = pPlaylistClient;
	}

	/**
	 * @return the exceptionView
	 */
	public String getExceptionView() {
		return mExceptionView;
	}

	/**
	 * @param pExceptionView the exceptionView to set
	 */
	@Required
	public void setExceptionView(String pExceptionView) {
		mExceptionView = pExceptionView;
	}
	
}
